import base64
import json
import random

from django.contrib.auth.hashers import make_password, check_password
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

# 注册
from user.models import User, Student


class RegisterView(View):
    def get(self, request):
        return render(request, 'Register/register.html')

    def  post(self,request):
        username =  request.POST.get('username')
        password = request.POST.get('password')
        qrpassword = request.POST.get('qrpassword')
        code =  request.POST.get('code')

        cache = get_redis_connection(alias='verify_codes')
        redis_code =  cache.get("code")
        if (code==redis_code):
            if password == qrpassword:
                user = User.objects.filter(username=username)
                if user:
                    return JsonResponse({
                        'status':200,
                        'msg':'该用户名已经存在，请重新输入！'
                    })
                else:
                    password = make_password(password)
                    User.objects.create(username=username,password=password,type=1)
                    return JsonResponse({
                        'status': 201,
                        'msg': '注册成功，请前往登陆！'
                    })
            else:
                return JsonResponse({
                    'status': 400,
                    'msg': "密码不一致，请重新输入！"
                })
        else:
            return JsonResponse({
                'status': 400,
                'msg': "验证码错误，请重新输入！"
            })

# 获取验证码
class GetCodeView(View):
    def get(self, request):
        num = '123456789'
        codes = ''
        for i in range(6):
            code = random.choice(num)
            codes += code
        cache = get_redis_connection(alias='verify_codes')
        cache.set("code", codes, 300)
        return JsonResponse({
            'status': 201,
            'code': codes
        }, json_dumps_params={'ensure_ascii': False})

# 登陆
class LoginView(View):
    def get(self,request):
        return render(request, 'Login/login.html')

    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('password')

        try:
            user = User.objects.get(username=username)
        except:
            return  JsonResponse({
                'status':404,
                'msg':'该用户不存在！'
            })
        if check_password(password,user.password):
            username =   base64.standard_b64encode(username.encode('utf-8')).decode('utf-8')
            response = JsonResponse({
                'status':201,
                'msg':'登陆成功'
            })
            response.set_signed_cookie('username',username,'abcd')
            return response
        else:
            return JsonResponse({
                'status': 400,
                'msg': '密码错误，请重新输入！'
            })




class Add_Student(View):
    def get(self,request):
        return render(request,'Students/add_student.html')

    def post(self,request):

        stu = Student.objects.filter(username=request.POST.get('username'))
        if stu:
            return  JsonResponse({
                'status':200,
                'msg':'该学生已经存在！'
            })
        else:
            Student.objects.create(
                username=request.POST.get('username'),
                phone=request.POST.get('phone'),
                sex=0 if request.POST.get('sex') == '男' else 1,
                age=request.POST.get('age'),
                address=request.POST.get('address'),
                classes_id=request.POST.get('class_id')
            )
        return JsonResponse({
            'status':201,
            'msg': '学生信息添加成功'
        })



class Check_Students(View):
    def get(self,request):
        pnum = request.GET.get("pnum",1)
        student  = Student.objects.all()
        paginator =Paginator(student,2)
        page = paginator.page(pnum)
        return render(request, 'Students/check_students.html', {
            'page': page
        })


class Check_Student(View):
    def get(self,request):
        student = Student.objects.all()
        return render(request,'Students/check_student.html',{
            'student':student
        })

def  Check_User_Id(request):
    if request.method =='POST':
        id = request.POST.get('id')
        student = Student.objects.filter(id=id)
        return render(request, 'Students/check_student.html', {
            'student':student
        })

def  Check_User_Name(request):
    if request.method =='POST':
        username = request.POST.get('username')
        student = Student.objects.filter(username=username)
        return render(request, 'Students/check_student.html', {
            'student':student
        })


class Delete_Student(View):
    def get(self,request):
        return render(request,'Students/delete_student.html')

class  Delete_User_Id(View):
    def delete(self,request,id):
        try:
            student  = Student.objects.get(id=id)
        except:
            return JsonResponse({
                'status': 404,
                'msg': '学生信息不存在'
            })
        student.delete()
        return JsonResponse({
            'status': 200,
            'msg': '学生信息已删除'
        })


class  Delete_User_Name(View):
    def delete(self,request):
        print(request.body)
        data = json.loads(request.body)
        print(data)
        name = ''
        try:
            student  = Student.objects.get(username=name)
        except:
            return JsonResponse({
                'status': 404,
                'msg': '学生信息不存在'
            })
        student.delete()
        return JsonResponse({
            'status': 200,
            'msg': '学生信息已删除'
        })